import os
import json
import base64
from server.func.FileOperate import copy_img

sql_path = "server/sql/"
user_dir = "users/"
group_dir = "groups/"
file_dir = "files/"
img_dir = "img_buf/"
history_dir = "history/"


def add_user(uid, password, name):
    """添加用户"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if not user_file in users:
        user_dic = {
            "password": password,
            "name": name,
            "img": "u"+str(uid)+".png",
            "sex": "boy",
            "search_accept": True,
            "explain": "",
            "Friend": {},
            "Group": {},
            "NewFriend": 0
        }
        with open(path + user_file, "w") as f:
            f.write(json.dumps(user_dic))
        dir_path = sql_path + history_dir + "u" + str(uid)
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        copy_img(uid, "friend")
        return True
    else:
        return False


def get_user_password(uid):
    """查询密码"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        with open(path + user_file, "r") as f:
            return json.load(f)["password"]
    else:
        return None


def get_user_img(uid):
    """查询头像图片地址"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        with open(path + user_file, "r") as f:
            return json.load(f)["img"]
    else:
        return "user_default.png"


def get_user_name(uid):
    """查询姓名"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        with open(path + user_file, "r") as f:
            return json.load(f)["name"]
    else:
        return uid


def delete_user(uid):
    """删除用户"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        os.remove(path + user_file)
        return True
    else:
        return False


def get_user_main(uid):
    """查询用户界面参数"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        with open(path + user_file, "r") as f:
            dic = json.load(f)
        return list(dic["Friend"].values()), list(dic["Group"].values()), dic["NewFriend"]
    else:
        return None


def change_new_friend_num(uid, num):
    """修改用户新朋友消息通知数"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        dic = json.load(open(path + user_file, "r"))
        dic["NewFriend"] = num
        with open(path + user_file, "w") as f:
            f.write(json.dumps(dic))
        return True
    else:
        return False


def add_new_friend_num(uid, num):
    """增加用户新朋友消息通知数"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        dic = json.load(open(path + user_file, "r"))
        dic["NewFriend"] += num
        with open(path + user_file, "w") as f:
            f.write(json.dumps(dic))
        return True
    else:
        return False


def change_msg_info_num(uid, target, mode, num):
    """修改消息通知数量"""
    user_path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    user_dic = json.load(open(user_path + user_file, "r"))
    if mode == "friend":
        if target in user_dic["Friend"].keys():
            friend = user_dic["Friend"][target]
            friend["msg_num"] = num
    else:
        if target in user_dic["Group"].keys():
            group = user_dic["Group"][target]
            group["msg_num"] = num
    with open(user_path + user_file, "w") as f:
        f.write(json.dumps(user_dic))
    return True


def add_msg_info(uid, target, mode, text, text_type, num=1):
    """添加消息通知"""
    user_path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    user_dic = json.load(open(user_path + user_file, "r"))
    if mode == "friend":
        if target in user_dic["Friend"].keys():
            friend = user_dic["Friend"][target]
            friend["msg_num"] += num
            if text_type == "text":
                friend["new_msg"] = text
            elif text_type == "img":
                friend["new_msg"] = u"[图片]"
            else:
                friend["new_msg"] = u"[文件]"
    else:
        if target in user_dic["Group"].keys():
            group = user_dic["Group"][target]
            group["msg_num"] += num
            if text_type == "text":
                group["new_msg"] = text
            elif text_type == "img":
                group["new_msg"] = u"[图片]"
            else:
                group["new_msg"] = u"[文件]"
    with open(user_path + user_file, "w") as f:
        f.write(json.dumps(user_dic))
    return True


def get_user_info(uid):
    """获取用户基础信息"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        with open(path + user_file, "r") as f:
            dic = json.load(f)
        return dic["name"], dic["img"], dic["sex"], dic["search_accept"], dic["explain"]
    else:
        return None


def save_img(img_path, img_base64):
    """保存头像图片"""
    path = sql_path + img_dir + img_path
    try:
        with open(path, "wb") as f:
            f.write(base64.b64decode(img_base64))
        return True
    except Exception as e:
        print(e)
        return False


def get_img(img_path):
    """获取头像图片"""
    path = sql_path + img_dir + img_path
    if os.path.exists(path):
        try:
            with open(path, "rb") as f:
                return str(base64.b64encode(f.read()))[2:-1]
        except:
            return None
    else:
        return None


def change_user_info(uid, info):
    """修改用户信息"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        dic = json.load(open(path + user_file, "r"))
        dic["name"] = info["name"]
        dic["img"] = "u" + str(uid) + ".png"
        dic["sex"] = info["sex"]
        dic["search_accept"] = info["search_accept"]
        dic["explain"] = info["explain"]
        with open(path + user_file, "w") as f:
            f.write(json.dumps(dic))
        return True
    else:
        return False


def change_password(uid, password):
    """修改密码"""
    path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(path)
    if user_file in users:
        dic = json.load(open(path + user_file, "r"))
        dic["password"] = password
        with open(path + user_file, "w") as f:
            f.write(json.dumps(dic))
        return True
    else:
        return False


def search(content):
    """搜索群聊或用户"""
    user_path = sql_path + user_dir
    group_path = sql_path + group_dir
    users = []
    groups = []
    all_users = os.listdir(user_path)
    all_groups = os.listdir(group_path)
    for user in all_users:
        dic = json.load(open(user_path + user, "r"))
        name = dic["name"]
        accept = dic["search_accept"]
        if accept and (content in name or content in user):
            try:
                users.append({
                    "name": name,
                    "uid": user[1:-5],
                    "img": dic["img"]
                })
            except:
                pass
    for group in all_groups:
        dic = json.load(open(group_path + group, "r"))
        name = dic["name"]
        accept = dic["search_accept"]
        if accept and (content in name or content in group):
            try:
                groups.append({
                    "name": name,
                    "uid": group[1:-5],
                    "img": dic["img"]
                })
            except:
                pass
    return users, groups


def friend_application(uid, target_uid):
    """好友申请"""
    user_path = sql_path + user_dir
    history_path = sql_path + history_dir
    user_file = "u" + str(uid) + ".json"
    target_user_file = "u" + str(target_uid) + ".json"
    user_history_dir = history_path + "u" + target_uid
    user_history_file = history_path + "u" + target_uid + "/new.json"
    users = os.listdir(user_path)
    if user_file in users and target_user_file in users:
        if not os.path.exists(user_history_dir):
            os.mkdir(user_history_dir)
        if not os.path.exists(user_history_file):
            with open(user_history_file, "w") as f:
                new_dic = {
                    "Friend": [{
                        "from": uid,
                        "isSolve": False
                    }],
                    "Group": []
                }
                f.write(json.dumps(new_dic))
        else:
            new_dic = json.load(open(user_history_file, "r"))
            new_dic["Friend"].append({
                "from": uid,
                "isSolve": False
            })
            with open(user_history_file, "w") as f:
                f.write(json.dumps(new_dic))
        add_new_friend_num(target_uid, 1)
        return True
    else:
        return False


def is_friend(my_uid, friend_uid):
    """判断是不是好友"""
    user_path = sql_path + user_dir
    user_file = "u" + str(my_uid) + ".json"
    users = os.listdir(user_path)
    if user_file in users:
        user_dic = json.load(open(user_path + user_file, "r"))
        if friend_uid in user_dic["Friend"].keys():
            return True
        else:
            return False
    else:
        return False


def get_remarks(my_uid, friend_uid):
    """查询好友昵称备注"""
    user_path = sql_path + user_dir
    user_file = "u" + str(my_uid) + ".json"
    users = os.listdir(user_path)
    if user_file in users:
        user_dic = json.load(open(user_path + user_file, "r"))
        if friend_uid in user_dic["Friend"].keys():
            return user_dic["Friend"][friend_uid]["name"]
        else:
            return None
    else:
        return None


def delete_friend(uid, friend_uid):
    """删除好友"""
    user_path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    friend_file = "u" + str(friend_uid) + ".json"
    if is_friend(uid, friend_uid) and is_friend(friend_uid, uid):
        user_dic = json.load(open(user_path + user_file, "r"))
        friends = user_dic["Friend"]
        del friends[friend_uid]
        with open(user_path + user_file, "w") as f:
            f.write(json.dumps(user_dic))
        friend_dic = json.load(open(user_path + friend_file, "r"))
        friends = friend_dic["Friend"]
        del friends[uid]
        with open(user_path + friend_file, "w") as f:
            f.write(json.dumps(friend_dic))
        return True
    else:
        return False


def change_remarks(uid, friend_uid, name):
    """修改好友备注"""
    user_path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    if is_friend(uid, friend_uid):
        user_dic = json.load(open(user_path + user_file, "r"))
        friend = user_dic["Friend"][friend_uid]
        friend["name"] = name
        with open(user_path + user_file, "w") as f:
            f.write(json.dumps(user_dic))
        return True
    else:
        return False


def response_friend_application(uid, from_uid, response):
    """回应好友申请"""
    user_path = sql_path + user_dir
    history_path = sql_path + history_dir
    user_file = "u" + str(uid) + ".json"
    from_user_file = "u" + str(from_uid) + ".json"
    user_history_file = history_path + "u" + uid + "/new.json"
    users = os.listdir(user_path)
    if user_file in users and from_user_file in users:
        if os.path.exists(user_history_file):
            new_dic = json.load(open(user_history_file, "r"))
            for dic in new_dic["Friend"]:
                if dic["from"] == from_uid:
                    dic["isSolve"] = True
            with open(user_history_file, "w") as f:
                f.write(json.dumps(new_dic))
            if response:
                if not is_friend(uid, from_uid):
                    user_dic = json.load(open(user_path + user_file, "r"))
                    user_dic["Friend"][from_uid] = {
                        "name": get_user_name(from_uid),
                        "uid": from_uid,
                        "new_msg": "",
                        "msg_num": 0,
                        "img": get_user_img(from_uid)
                    }
                    with open(user_path + user_file, "w") as f:
                        f.write(json.dumps(user_dic))
                if not is_friend(from_uid, uid):
                    from_user_dic = json.load(open(user_path + from_user_file, "r"))
                    from_user_dic["Friend"][uid] = {
                        "name": get_user_name(uid),
                        "uid": uid,
                        "new_msg": "",
                        "msg_num": 0,
                        "img": get_user_img(uid)
                    }
                    with open(user_path + from_user_file, "w") as f:
                        f.write(json.dumps(from_user_dic))
            return True
        else:
            return False
    else:
        return False


def get_new_friend(uid):
    """获取新朋友消息"""
    user_history_file = sql_path + history_dir + "u" + uid + "/new.json"
    if os.path.exists(user_history_file):
        new_dic = json.load(open(user_history_file, "r"))
        return new_dic["Friend"], new_dic["Group"]
    else:
        return [], []


def clear_new_friend(uid, mode):
    """清空新朋友消息"""
    user_history_file = sql_path + history_dir + "u" + uid + "/new.json"
    if os.path.exists(user_history_file):
        new_dic = json.load(open(user_history_file, "r"))
        if mode == "user":
            new_dic["Friend"].clear()
        else:
            new_dic["Group"].clear()
        with open(user_history_file, "w") as f:
            f.write(json.dumps(new_dic))
        return True
    else:
        return False


def get_history(uid, target, mode: str):
    """获取历史聊天记录, mode为friend或group"""
    if mode == "friend":
        history_file = sql_path + history_dir + "u" + uid + "/" + "u" + target + ".json"
    else:
        history_file = sql_path + history_dir + "g" + target + "/" + "g" + target + ".json"
    if os.path.exists(history_file):
        return json.load(open(history_file, "r"))
    else:
        return {"history": []}


def send_message(uid, target, mode, msg_dic):
    """转发消息"""
    history_path = sql_path + history_dir
    if mode == "friend":
        if not os.path.exists(history_path + "u" + uid + "/"):
            os.mkdir(history_path + "u" + uid + "/")
        if not os.path.exists(history_path + "u" + target + "/"):
            os.mkdir(history_path + "u" + target + "/")
        user_path = history_path + "u" + uid + "/u" + target + ".json"
        target_path = history_path + "u" + target + "/u" + uid + ".json"
        if os.path.exists(user_path):
            user_dic = json.load(open(user_path, "r"))
        else:
            user_dic = {"history": []}
        user_dic["history"].append(msg_dic)
        add_msg_info(uid, target, mode, msg_dic["text"], msg_dic["bubble_type"], num=0)
        with open(user_path, "w", encoding="utf-8") as f:
            f.write(json.dumps(user_dic))
        if os.path.exists(target_path):
            target_dic = json.load(open(target_path, "r"))
        else:
            target_dic = {"history": []}
        msg_dic["isMe"] = False
        target_dic["history"].append(msg_dic)
        add_msg_info(target, uid, mode, msg_dic["text"], msg_dic["bubble_type"])
        with open(target_path, "w", encoding="utf-8") as f:
            f.write(json.dumps(target_dic))
    else:
        if not os.path.exists(history_path + "g" + target + "/"):
            os.mkdir(history_path + "g" + target + "/")
        group_path = history_path + "g" + target + "/g" + target + ".json"
        if os.path.exists(group_path):
            group_dic = json.load(open(group_path, "r"))
        else:
            group_dic = {"history": []}
        group_dic["history"].append(msg_dic)
        add_msg_info(uid, target, mode, msg_dic["text"], msg_dic["bubble_type"], num=0)
        members = get_group_members(target)
        for member in members:
            if not member == uid:
                add_msg_info(member, target, mode, msg_dic["text"], msg_dic["bubble_type"])
        with open(group_path, "w", encoding="utf-8") as f:
            f.write(json.dumps(group_dic))
    return True


def add_group(uid, name):
    """新建群聊"""
    user_path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(user_path)
    if user_file in users:
        group_dir_path = sql_path + group_dir
        group_uid = str(len(os.listdir(group_dir_path)))
        name = name
        img = "g"+str(group_uid)+".png"
        explain = ""
        search_accept = True
        master = uid
        members = [uid]
        group_dic = {
            "uid": group_uid,
            "name": name,
            "img": img,
            "explain": explain,
            "search_accept": search_accept,
            "master": master,
            "members": members
        }
        with open(group_dir_path + "g" + group_uid + ".json", "w") as f:
            f.write(json.dumps(group_dic))
        dir_path = sql_path + history_dir + "g" + str(group_uid)
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        copy_img(group_uid, "group")
        dic = json.load(open(user_path + user_file, "r"))
        dic["Group"][group_uid] = {
            "name": name,
            "uid": group_uid,
            "new_msg": "",
            "msg_num": 0,
            "img": img
        }
        with open(user_path + user_file, "w") as f:
            f.write(json.dumps(dic))
        return True
    else:
        return False


def get_group_info(uid):
    """获取群聊信息"""
    group_dir_path = sql_path+group_dir
    group_file = "g"+str(uid)+".json"
    if group_file in os.listdir(group_dir_path):
        return json.load(open(group_dir_path + group_file, "r"))
    else:
        return None


def change_group_info(uid, info):
    """修改群聊信息"""
    path = sql_path + group_dir
    group_file = "g" + str(uid) + ".json"
    groups = os.listdir(path)
    if group_file in groups:
        dic = json.load(open(path + group_file, "r"))
        dic["name"] = info["name"]
        dic["img"] = "g" + str(uid) + ".png"
        dic["search_accept"] = info["search_accept"]
        dic["explain"] = info["explain"]
        with open(path + group_file, "w") as f:
            f.write(json.dumps(dic))
        members = dic["members"]
        for member in members:
            user_path = sql_path + user_dir
            user_file = "u" + str(member) + ".json"
            user_dic = json.load(open(user_path + user_file, "r"))
            group = user_dic["Group"][uid]
            group["name"] = dic["name"]
            with open(user_path + user_file, "w") as f:
                f.write(json.dumps(user_dic))
        return True
    else:
        return False


def get_group_members(uid):
    """获取群聊成员uid"""
    path = sql_path + group_dir
    group_file = "g" + str(uid) + ".json"
    groups = os.listdir(path)
    if group_file in groups:
        dic = json.load(open(path + group_file, "r"))
        return dic["members"]
    else:
        return []


def get_group_master(group_uid):
    """获取群主uid"""
    path = sql_path + group_dir
    group_file = "g" + str(group_uid) + ".json"
    groups = os.listdir(path)
    if group_file in groups:
        dic = json.load(open(path + group_file, "r"))
        return dic["master"]
    else:
        return None


def group_application(uid, target_uid):
    """群聊申请"""
    user_path = sql_path + user_dir
    history_path = sql_path + history_dir
    user_file = "u" + str(uid) + ".json"
    master_uid = get_group_master(target_uid)
    target_user_file = "u" + str(master_uid) + ".json"
    user_history_dir = history_path + "u" + master_uid
    user_history_file = history_path + "u" + master_uid + "/new.json"
    users = os.listdir(user_path)
    if user_file in users and target_user_file in users:
        if not os.path.exists(user_history_dir):
            os.mkdir(user_history_dir)
        if not os.path.exists(user_history_file):
            with open(user_history_file, "w") as f:
                new_dic = {
                    "Friend": [],
                    "Group": [{
                        "from": uid,
                        "isSolve": False,
                        "type": "group_apply",
                        "group_uid":target_uid,
                        "group": get_group_info(target_uid)["name"]
                    }]
                }
                f.write(json.dumps(new_dic))
        else:
            new_dic = json.load(open(user_history_file, "r"))
            new_dic["Group"].append({
                "from": uid,
                "isSolve": False,
                "type": "group_apply",
                "group_uid": target_uid,
                "group": get_group_info(target_uid)["name"]
            })
            with open(user_history_file, "w") as f:
                f.write(json.dumps(new_dic))
        add_new_friend_num(master_uid, 1)
        return True
    else:
        return False


def is_group(uid, group_uid):
    """判断加没加入这个群聊"""
    user_path = sql_path + user_dir
    user_file = "u" + str(uid) + ".json"
    users = os.listdir(user_path)
    if user_file in users:
        user_dic = json.load(open(user_path + user_file, "r"))
        if group_uid in user_dic["Group"].keys():
            return True
        else:
            return False
    else:
        return False


def add_group_member(group_uid, member_uid):
    """添加群聊成员"""
    path = sql_path + group_dir
    group_file = "g" + str(group_uid) + ".json"
    groups = os.listdir(path)
    if group_file in groups:
        dic = json.load(open(path + group_file, "r"))
        if member_uid not in dic["members"]:
            dic["members"].append(member_uid)
        with open(path + group_file, "w") as f:
            f.write(json.dumps(dic))
        return True
    else:
        return False


def response_group_application(uid, group_uid, from_uid, response):
    """回复群聊申请"""
    user_path = sql_path + user_dir
    history_path = sql_path + history_dir
    user_file = "u" + str(uid) + ".json"
    from_user_file = "u" + str(from_uid) + ".json"
    user_history_file = history_path + "u" + uid + "/new.json"
    users = os.listdir(user_path)
    if user_file in users and from_user_file in users:
        if os.path.exists(user_history_file):
            new_dic = json.load(open(user_history_file, "r"))
            for dic in new_dic["Group"]:
                if dic["type"] == "group_apply" and dic["from"] == from_uid:
                    dic["isSolve"] = True
            with open(user_history_file, "w") as f:
                f.write(json.dumps(new_dic))
            if response:
                if not is_group(from_uid, group_uid):
                    from_user_dic = json.load(open(user_path + from_user_file, "r"))
                    from_user_dic["Group"][group_uid] = {
                        "name": get_group_info(group_uid)["name"],
                        "uid": group_uid,
                        "new_msg": "",
                        "msg_num": 0,
                        "img": "g"+str(group_uid)+".png"
                    }
                    with open(user_path + from_user_file, "w") as f:
                        f.write(json.dumps(from_user_dic))
                add_group_member(group_uid, from_uid)
            return True
        else:
            return False
    else:
        return False


def out_group(group_uid, member_uid):
    """退出群聊"""
    path = sql_path + group_dir
    group_file = "g" + str(group_uid) + ".json"
    user_path = sql_path + user_dir
    user_file = "u" + str(member_uid) + ".json"
    groups = os.listdir(path)
    if group_file in groups:
        dic = json.load(open(path + group_file, "r"))
        if member_uid in dic["members"]:
            dic["members"].remove(member_uid)
        with open(path + group_file, "w") as f:
            f.write(json.dumps(dic))
        if is_group(member_uid, group_uid):
            user_dic = json.load(open(user_path + user_file, "r"))
            groups = user_dic["Group"]
            del groups[group_uid]
            with open(user_path + user_file, "w") as f:
                f.write(json.dumps(user_dic))
            return True
        else:
            return False
    else:
        return False


def delete_group(group_uid):
    """删除群聊"""
    members = get_group_members(group_uid)
    for member_uid in members:
        out_group(group_uid, member_uid)
    path = sql_path + group_dir
    group_file = "g" + str(group_uid) + ".json"
    groups = os.listdir(path)
    if group_file in groups:
        os.remove(path + group_file)
        return True
    else:
        return False